<template>
    <div class="commodity" :style="{ 'height': productsHeight }">
        <div class="page_img"></div>
        <div class="header">
            <van-nav-bar title="商品" />
        </div>
        <searchHome v-model:value="queryParams.content" @onSubmit="onRefresh" @screenIsShow_on="screenIsShow_on" />
        <div class="commodity_classify">
            <div class="commodity_classify_item" @click="categoryIsShow = true">
                <span>{{ queryParams.categoryIdList.length ? '多品类' : '商品类目' }}</span>
                <img src="@/assets/commodity/icon_heisexiasanjiao.png" alt="">
            </div>
            <category :isShow="categoryIsShow" v-model:value="queryParams.categoryIdList" :multiple="true"
                @leftClick="categoryIsShow = false" @onSubmit="categorySubmit" />
            <div class="commodity_classify_item" @click="screenIsShow = true; screenType = 'repertory'">
                <span>{{ queryParams.shelvesStatusName === '' ? '库存状态' : queryParams.shelvesStatusName }}</span>
                <img src="@/assets/commodity/icon_heisexiasanjiao.png" alt="">
            </div>
            <div class="commodity_classify_item" @click="screenIsShow = true; screenType = 'merchants'">
                <span>{{ queryParams.recruiterDeptIdName === '' ? '部门' : queryParams.recruiterDeptIdName }}</span>
                <img src="@/assets/commodity/icon_heisexiasanjiao.png" alt="">
            </div>
            <!-- <div class="commodity_classify_div" @click="screenIsShow = true; screenType = 'all'">
                <img src="@/assets/commodity/icon_shaixuan.png" alt="">
            </div> -->
            <screenHome :isShow="screenIsShow" @onReset="screenReset" @onSubmit="screenSubmit"
                @close="screenIsShow = true">
                <searchScreen :type="screenType" v-model:shelvesStatus="queryParams.shelvesStatus"
                    v-model:shelvesStatusName="queryParams.shelvesStatusName"
                    v-model:recruiterType="queryParams.recruiterType"
                    v-model:recruiterDeptId="queryParams.recruiterDeptId"
                    v-model:recruiterDeptIdName="queryParams.recruiterDeptIdName"
                    v-model:recruiterUserId="queryParams.recruiterUserId" v-model:inStartTime="queryParams.inStartTime"
                    v-model:inEndTime="queryParams.inEndTime" v-model:outStockTag="queryParams.outStockTag"
                    ref="searchScreenRef" />
            </screenHome>
        </div>
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" :style="{ 'height': refreshHeight }">
            <van-list v-model:loading="loading" :finished="finished" @load="onLoad">
                <template v-slot:finished>
                    <div class="nothing_div" v-if="list.length == 0 && !refreshing">
                        <van-image :src="nothingData"></van-image>
                        <div class="nothing_font">暂无数据</div>
                    </div>
                </template>
                <van-swipe-cell v-for="item in list" :key="item.id">
                    <commodityList :data="item" @click="routerGo(item.id)" />
                    <template #right>
                        <div class="parmay_list">
                            <div class="parmay" v-if="item.shelvesStatus === 2"
                                @click="offShelf(item)" v-throttle:click :style="{color:'#FC2540',backgroundColor:'#F6FAFF'}" >
                                <van-image :src="xiajiaImg" />
                                <div>下架</div>
                            </div>
                            <div class="parmay" v-if="item.shelvesStatus !== 2"
                                @click="grounding(item.id)" v-throttle:click :style="{color:'#19D11B',backgroundColor:'#F6FAFF'}" >
                                <van-image :src="shangjiaImg" />
                                <div>上架</div>
                            </div>
                            <div class="parmay" v-if="item.shelvesStatus === 2"
                                @click="outbound(item)" v-throttle:click :style="{color:'#0094FF',backgroundColor:'#F6FAFF'}" >
                                <van-image :src="chukuImg" />
                                <div>出库</div>
                            </div>
                            
                           
                        </div>
                        
                    </template>
                </van-swipe-cell>
            </van-list>
        </van-pull-refresh>

        <van-overlay :show="overlayShow" @click="overlayShow = false" z-index="6001">
            <div class="wrapper" @click.stop>
                <div class="wrapper_div">
                    <van-image :src="colseImg" @click="close"></van-image>
                    <div class="title">下架原因</div>
                    <van-form @submit="onSubmit">
                        <van-field maxlength="200" show-word-limit v-model="message" rows="6" label="" type="textarea"
                            placeholder="请输入下架原因，不超过200字符" :border="false"
                            :rules="[{ required: true, trigger: 'onBlur', message: '请输入下架原因' }]" />
                        <van-button class="button" round block type="primary" native-type="submit" v-throttle:click>
                            提交确认
                        </van-button>
                    </van-form>
                </div>
            </div>
        </van-overlay>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, onActivated } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { queryProductList } from '@/api/productList/index'
import { getEnvValue } from "@/utils/index";
import { setUpDownShelves } from '@/api/productHome/index'
import { showSuccessToast } from "vant";
// 类目
import category from '@/components/category/index.vue'
// 头部搜索框
import searchHome from './components/searchHome/indexNew.vue'
// 列表
import commodityList from './components/commodityList/index.vue'
// 搜索筛选
import screenHome from './components/screenHome/index.vue'
import searchScreen from './components/searchScreen/index.vue'

const nothingData = new URL("@/assets/porduct/icon_zanwushuju.png", import.meta.url).href
const colseImg = new URL("@/assets/approval/close.png", import.meta.url).href;

const router = useRouter();
const route = useRoute();
const overlayShow = ref(false)
const message = ref('')
const detailInfo = ref<any>({});
const searchScreenRef = ref()
// 类目开关
const categoryIsShow = ref(false)
// 筛选弹框
const screenIsShow = ref<boolean>(false)
const screenType = ref('all')

const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);
const list = ref<Array<any>>([]);
// 限制连续刷新数据重复问题
const refreFlag = ref(true)

// 查询列表参数
const queryParams = ref<any>({
    content: '',
    categoryId: '',
    categoryName: '',
    recruiterType: '',
    recruiterUserId: '',
    recruiterDeptId: '',
    recruiterDeptIdName: '',
    shelvesStatus: '',
    shelvesStatusName: '',
    inStartTime: '',
    inEndTime: '',
    pageSize: 10,
    pageNum: 1,
    outStockTag: '',
    categoryIdList: []
})

const productsHeight = ref()
const refreshHeight = ref()
const defaultPhoneHeight = ref(0) //屏幕默认高度
const nowPhoneHeight = ref(0) //屏幕现在的高度
const emits = defineEmits(['doShow'])
const vantListScrollTop = ref<any>(0) // 滚动位置

//图片
const xiajiaImg = new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href
const shangjiaImg = new URL("@/assets/newui/productList/icon_shangjia@2x.png", import.meta.url).href 
const chukuImg = new URL("@/assets/newui/productList/icon_chuku@2x.png", import.meta.url).href 
// 在组件挂载完成后添加事件监听器
onMounted(() => {
    queryParams.value.shelvesStatus = route.query.shelvesStatus || ''
    queryParams.value.shelvesStatusName = route.query.shelvesStatusName || ''
    defaultPhoneHeight.value = window.innerHeight;
    // 添加事件监听器
    window.addEventListener('resize', handleResize);
    functionScroll('init')
})
// 处理窗口大小变化的函数
const handleResize = () => {
    nowPhoneHeight.value = window.innerHeight;
};
// 在组件卸载前移除事件监听器
onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    functionScroll('delete')
});
/** 缓存页面进度条 */
const functionScroll = (type: string) => {
    const dom: any = document.querySelector('.van-pull-refresh')
    if (type === 'init') {
        dom?.addEventListener('scroll', (e: any) => {
            vantListScrollTop.value = e.target.scrollTop
        })
    } else if (type === 'delete') {
        dom?.removeEventListener('scroll', () => { });
    } else if (type === 'black') {
        dom.scrollTop = vantListScrollTop.value
    }
}
onActivated(() => {
    functionScroll('black')
})
watch(nowPhoneHeight, () => {
    if (defaultPhoneHeight.value != nowPhoneHeight.value) {
        // 当软键盘弹出,改变bottomIsSHow变量然后去控制bottom的显示与隐藏
        productsHeight.value = '100vh'
        refreshHeight.value = 'calc(100vh - 42.6666vw)'
        emits('doShow', false)
    } else {
        // 相等代表软键盘收起后,与上同理
        productsHeight.value = 'calc(100vh - 10.333333vw)'
        refreshHeight.value = 'calc(100vh - 56vw)'
        emits('doShow', true)
    }
})
// 获取列表数据
const getList = async () => {
    const { data } = await queryProductList(queryParams.value)
    const { rows = [], total = 0 } = data
    refreFlag.value = true
    // 空数据 停止加载
    if (rows.length == 0) {
        list.value = [];
        finished.value = true;
        return;
    }
    // 有数据 赋值列表 加载状态结束
    rows.forEach((item: any) => {
        finished.value = false;
        if (item.productImage) {
            item.productImages = getEnvValue("VITE_APP_PIC_URL") + item.productImage.split(',')[0];
        } else {
            item.productImages = "";
        }
        list.value.push(item);
    });
    loading.value = false;
    refreshing.value = false;
    // 如果list长度大于等于总数据条数，数据全部加载完成
    if (list.value.length >= total) {
        finished.value = true; //结束加载
    }
}

// 筛选重置事件
const screenReset = () => {
    if (screenType.value == 'all') {
        queryParams.value = {
            content: '',
            categoryName: '',
            recruiterUserId: '',
            recruiterType: '',
            recruiterDeptId: '',
            recruiterDeptIdName: '',
            shelvesStatus: '',
            shelvesStatusName: '',
            inStartTime: '',
            inEndTime: '',
            pageSize: 10,
            pageNum: 1,
            outStockTag: '',
            categoryIdList: []
        }
    } else if (screenType.value == 'repertory') {
        queryParams.value.pageNum = 1
        queryParams.value.shelvesStatus = ''
        queryParams.value.shelvesStatusName = ''
    } else {
        queryParams.value.recruiterType = ''
        queryParams.value.recruiterDeptId = ''
        queryParams.value.recruiterDeptIdName = ''
        queryParams.value.recruiterUserId = ''
        searchScreenRef.value.recruiterList = []
    }
}
// 筛选完成事件
const screenSubmit = () => {
    screenIsShow.value = false
    onRefresh()
}
// 筛选完成事件
const screenIsShow_on = () => {
    screenIsShow.value = true;
    screenType.value = 'all'
}
// 跳转商品详情
const routerGo = (id: string | number) => {
    router.push({
        path: `/productHomeDetail/${id}`,
        query: {
            shelvesStatus: queryParams.value.shelvesStatus,
            shelvesStatusName: queryParams.value.shelvesStatusName
        }
    })
}

/** 上架 */
const grounding = async (id: string | number) => {
    router.push({
        path: '/grounding',
        query: {
            id: id
        }
    })
}
/** 下架 */
const offShelf = async (row: any) => {
    overlayShow.value = true
    detailInfo.value = row
}
/** 下架关闭 */
const close = () => {
    overlayShow.value = false
}
/** 下架建议提交 */
const onSubmit = async () => {
    await setUpDownShelves({
        stockProductsBoList: [
            {
                productsId: detailInfo.value.id,
                putType: 1, // 2上架 1下架
                offShelfRemark: message.value,
                locationCode: detailInfo.value.stockInfo.locationName,
                stockCode: detailInfo.value.stockCode
            }
        ]
    })
    showSuccessToast({ type: 'success', message: '下架成功' });
    overlayShow.value = false
    queryParams.value.pageNum = 1
    list.value = []
    onLoad();
    // router.back()
}
/** 出库 */
const outbound = async (row: any) => {
    router.push({
        path: '/outboundType',
        query: {
            detailInfo: JSON.stringify(row)
        }
    })
}

/** 加载更多 */
const onLoad = async () => {
    getList();
    queryParams.value.pageNum++;
};
/** 下拉 */
const onRefresh = () => {
    if (refreFlag.value) {
        refreFlag.value = false
        finished.value = false; // 清空列表数据
        refreshing.value = false;
        loading.value = true; // 加载状态
        queryParams.value.pageNum = 1; // 分页数赋值为1
        list.value = []; // 清空数组
        onLoad(); // 重新加载数据
    } else {
        finished.value = false;
        refreshing.value = false;
    }
};
// 商品类目选择完成
const categorySubmit = () => {
    categoryIsShow.value = false
    onRefresh()
}


</script>
<script lang="ts">
export default { name: 'ProductLists' }
</script>

<style lang="less" scoped>
@import url(./components/style/index.less);

:deep(.screenHome_bg) {
    top: 188px;
}

:deep(.commodity_classify) {
    margin-bottom: 0px !important;
    border-radius: 15px 15px 0px 0px;
    
    
}

.commodity {
    .header {
        filter: blur(0px);
        height: 90px;
        padding-top: 44px;
        box-sizing: border-box;
        width: 100%;
        position: relative;
        z-index: 6003;

        :deep(.van-icon-arrow-left) {
            color: #1a1b1c !important;
        }

        :deep(.van-nav-bar__title) {
            color: #1a1b1c !important;
            font-size: 18px !important;
            font-weight: 600 !important;

        }

        :deep(.van-nav-bar) {
            background: none !important;

            &::after {
                display: none !important;
            }
        }

        :deep(.van-nav-bar__content) {
            background-color: transparent !important;
        }
    }

    .page_img {
        background: url("@/assets/newui/productList/icon_shangpintu@2x.png");
        background-size: 100% 100%;
        position: absolute;
        width: 60px;
        height: 60px;
        top: 54px;
        right: 63px;

    }

    background: url(/src/assets/newui/productList/icon_shangpinbeijing@2x.png);
    background-size: 100%;
    background-repeat: no-repeat;
    position: relative;
}
.parmay_list{
    display: flex;
    align-items: center;
    height: 100%;
    .parmay{
        width: 70px;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        :deep(.van-image){
            width: 46px;
            height: 46px;
            margin-bottom: 10px;
        }
    }
}

</style>